package com.hotely5d.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hotely5d.dao.CategoryMapper;
import com.hotely5d.dao.OrdersMapper;
import com.hotely5d.dao.RoomMapper;
import com.hotely5d.entity.Category;
import com.hotely5d.entity.Orders;
import com.hotely5d.entity.Room;
import com.hotely5d.entity.model.Result;
import com.hotely5d.entity.model.StatusCode;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class RoomService {

    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private AppointmentService appointmentService;
    @Autowired
    private OrdersMapper ordersMapper;

    public List<Room> findAll() {
        // 只查询未删除的房间
        return roomMapper.selectList(new EntityWrapper<Room>().eq("deleted", 0));
    }

    public Page<Room> search(Page<Room> page,Room room) {
        List<Room> list = roomMapper.selectPage(page, getEntityWrapper(room));
        for (Room r : list) {
            Category category = categoryMapper.selectById(r.getCategoryId());
            r.setCategory(category);
        }
        return page.setRecords(list);
    }

    public List<Room> search(Room room) {
        return roomMapper.selectList(getEntityWrapper(room));
    }

    //条件构造器
    private EntityWrapper<Room> getEntityWrapper(Room room){
        EntityWrapper<Room> entityWrapper = new EntityWrapper<>();
        // 只查询未删除的房间
        entityWrapper.eq("deleted", 0);
        if(null != room){
            if(!StringUtils.isEmpty(room.getRoomNum())){
                entityWrapper.like("room_num",String.valueOf(room.getRoomNum()));
            }
            if(!StringUtils.isEmpty(room.getCategoryId())){
                entityWrapper.eq("category_id", room.getCategoryId());
            }
            if(!StringUtils.isEmpty(room.getStatus())){
                entityWrapper.eq("status", room.getStatus());
            }
        }
        return entityWrapper;
    }

    public Result modify(Room room) {
        Integer count = roomMapper.selectCount(new EntityWrapper().eq("room_num", room.getRoomNum()).notIn("id", room.getId()));
        if(count != 0){
            return new Result(false, StatusCode.ERROR,"房间号已存在");
        }
        roomMapper.updateById(room);
        return new Result(true, StatusCode.OK,"修改成功");
    }

    public Result add(Room room) {
        Integer count = roomMapper.selectCount(new EntityWrapper<Room>().eq("room_num", room.getRoomNum()).eq("deleted", 0));
        if(count != 0){
            return new Result(false, StatusCode.ERROR,"房间号已存在");
        }
        // 设置默认值：未删除
        room.setDeleted(0);
        roomMapper.insert(room);
        return new Result(true, StatusCode.OK,"新增成功");
    }

    public Room findById(Integer id) {
        // 只查询未删除的房间
        List<Room> rooms = roomMapper.selectList(new EntityWrapper<Room>().eq("id", id).eq("deleted", 0));
        if (rooms.isEmpty()) {
            return null;
        }
        Room room = rooms.get(0);
        //1.查询房型
        Category category = categoryMapper.selectById(room.getCategoryId());
        room.setCategory(category);
        //2.查询今日是否可(预订/入住)
        ArrayList<Integer> statusList = new ArrayList<>();
        statusList.add(1);//已预订
        statusList.add(2);//已入住
        List<Orders> ordersList = ordersMapper.selectList(new EntityWrapper()
                .eq("room_id", room.getId())
                .in("status", statusList));
        if(ordersList.size() == 0){
            room.setCanUse(true);
            return room;
        }

        String startDate = DateFormatUtils.format(ordersList.get(0).getStartTime(),"yyyy-MM-dd");
        String currDate = DateFormatUtils.format(new Date(),"yyyy-MM-dd");
        //不为0，判断当前日期是否在入住日期+居住天数之后
        room.setCanUse(appointmentService.canAppointment(currDate,startDate,ordersList.get(0).getDays()));
        //3.查询已被(预订/入住)的日期
        List<String> dateList = new ArrayList();
        for (int i = 0; i < ordersList.get(0).getDays() ; i++) {
            try {
                Date date = DateUtils.parseDate(startDate, "yyyy-MM-dd");
                Date rs = DateUtils.addDays(date, i);
                dateList.add(DateFormatUtils.format(rs,"yyyy-MM-dd"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        room.setNotUseDateList(dateList);
        return room;
    }

    public void removeById(Integer id) {
        // 实现逻辑删除：将deleted字段设置为1
        Room room = new Room();
        room.setId(id);
        room.setDeleted(1);
        roomMapper.updateById(room);
    }

    /**
     * 导出房间数据到Excel
     * @param room 查询条件
     * @param response HTTP响应对象
     * @throws IOException
     */
    public void exportRoomData(Room room, HttpServletResponse response) throws IOException {
        // 查询数据
        List<Room> roomList = search(room);

        // 为每个房间设置房型信息
        for (Room r : roomList) {
            Category category = categoryMapper.selectById(r.getCategoryId());
            r.setCategory(category);
        }

        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("房间信息");

        // 创建标题行样式
        CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        headerStyle.setBorderTop(BorderStyle.MEDIUM);
        headerStyle.setBorderBottom(BorderStyle.MEDIUM);
        headerStyle.setBorderLeft(BorderStyle.MEDIUM);
        headerStyle.setBorderRight(BorderStyle.MEDIUM);
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerFont.setColor(IndexedColors.WHITE.getIndex());
        headerFont.setFontHeightInPoints((short) 12);
        headerStyle.setFont(headerFont);

        // 创建数据行样式
        CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setBorderTop(BorderStyle.THIN);
        dataStyle.setBorderBottom(BorderStyle.THIN);
        dataStyle.setBorderLeft(BorderStyle.THIN);
        dataStyle.setBorderRight(BorderStyle.THIN);
        dataStyle.setAlignment(HorizontalAlignment.CENTER);
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 创建价格样式（右对齐，保留两位小数）
        CellStyle priceStyle = workbook.createCellStyle();
        priceStyle.setBorderTop(BorderStyle.THIN);
        priceStyle.setBorderBottom(BorderStyle.THIN);
        priceStyle.setBorderLeft(BorderStyle.THIN);
        priceStyle.setBorderRight(BorderStyle.THIN);
        priceStyle.setAlignment(HorizontalAlignment.RIGHT);
        priceStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        DataFormat format = workbook.createDataFormat();
        priceStyle.setDataFormat(format.getFormat("¥#,##0.00"));

        // 创建数字样式（居中对齐）
        CellStyle numberStyle = workbook.createCellStyle();
        numberStyle.setBorderTop(BorderStyle.THIN);
        numberStyle.setBorderBottom(BorderStyle.THIN);
        numberStyle.setBorderLeft(BorderStyle.THIN);
        numberStyle.setBorderRight(BorderStyle.THIN);
        numberStyle.setAlignment(HorizontalAlignment.CENTER);
        numberStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.setHeight((short) 600); // 设置标题行高度
        String[] headers = {"房间ID", "房间号", "房型名称", "价格(元)", "可住人数", "床位数", "面积(㎡)", "状态"};

        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }

        // 填充数据
        for (int i = 0; i < roomList.size(); i++) {
            Row row = sheet.createRow(i + 1);
            row.setHeight((short) 450); // 设置数据行高度
            Room r = roomList.get(i);

            // 房间ID
            Cell cell0 = row.createCell(0);
            cell0.setCellValue(r.getId());
            cell0.setCellStyle(numberStyle);

            // 房间号
            Cell cell1 = row.createCell(1);
            cell1.setCellValue(r.getRoomNum());
            cell1.setCellStyle(dataStyle);

            // 房型名称
            Cell cell2 = row.createCell(2);
            cell2.setCellValue(r.getCategory() != null ? r.getCategory().getCategoryName() : "未分类");
            cell2.setCellStyle(dataStyle);

            // 价格
            Cell cell3 = row.createCell(3);
            cell3.setCellValue(r.getCategory() != null && r.getCategory().getPrice() != null ?
                r.getCategory().getPrice().doubleValue() : 0);
            cell3.setCellStyle(priceStyle);

            // 可住人数
            Cell cell4 = row.createCell(4);
            cell4.setCellValue(r.getCategory() != null ? r.getCategory().getLiveNum() : 0);
            cell4.setCellStyle(numberStyle);

            // 床位数
            Cell cell5 = row.createCell(5);
            cell5.setCellValue(r.getCategory() != null ? r.getCategory().getBedNum() : 0);
            cell5.setCellStyle(numberStyle);

            // 面积
            Cell cell6 = row.createCell(6);
            String area = r.getCategory() != null && r.getCategory().getArea() != null ?
                r.getCategory().getArea() : "未知";
            cell6.setCellValue(area);
            cell6.setCellStyle(dataStyle);

            // 状态
            Cell cell7 = row.createCell(7);
            cell7.setCellValue(r.getStatus() == 1 ? "正常" : "停用");
            cell7.setCellStyle(dataStyle);
        }

        // 设置列宽（更精确的控制）
        sheet.setColumnWidth(0, 2500);  // 房间ID
        sheet.setColumnWidth(1, 3000);  // 房间号
        sheet.setColumnWidth(2, 4500);  // 房型名称
        sheet.setColumnWidth(3, 3500);  // 价格
        sheet.setColumnWidth(4, 3000);  // 可住人数
        sheet.setColumnWidth(5, 3000);  // 床位数
        sheet.setColumnWidth(6, 3500);  // 面积
        sheet.setColumnWidth(7, 2500);  // 状态

        // 冻结首行（标题行）
        sheet.createFreezePane(0, 1);

        // 设置响应头
        String fileName = "房间信息_" + DateFormatUtils.format(new Date(), "yyyyMMdd_HHmmss") + ".xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 输出到响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }
}
